<template>
    <div>
      <n-grid :x-gap="10" :y-gap="5" :cols="4">
        <n-grid-item>
          <n-button type="success" size="medium" 
          @click="handleAdd">
            新增角色
          </n-button>
        </n-grid-item>
      </n-grid>
      <n-config-provider>
      <n-data-table
        :columns="columns"
        :data="roleList"
        :pagination="pagination"
        class="product-table"
      />
    </n-config-provider>
    <n-drawer v-model:show="drawerShow" 
    :width="400" placement="right">
        <n-drawer-content 
        :title="editData?'编辑角色':'新增角色'">
            <RoleForm :row-data="editData"
            @update-list="handleRefresh"/>
        </n-drawer-content>
    </n-drawer>
    </div>
</template>
  
  <script setup>
  import { useMessage,NButton, useDialog, NTag } from 'naive-ui';
  import { ref,h } from 'vue';
  import { useRouter } from 'vue-router';
  import { routes } from '../../router';
  import RoleForm from './components/RoleForm.vue';
  import {usePermission} from '../../hooks/permission.js'
  import { roleGetApi,roleDelApi,roleUpdateApi} from '../../api/user';
  const roleList = ref([]);
  roleGetApi().then((res)=>{
    roleList.value = res.data.data
  })
  const{canUse}=usePermission(['C001'])
  //表格配置
  function createColumns({
    edit,
    del
  }) {
    let columnArr= [
      {
        title: "角色ID",
        key: "_id"
      },
      {
        title: "角色名称",
        key: "roleName"
      },
      {
        title: "角色权限",
        key: "permission",
        render(row) { //自定义渲染表格内容的函数
          let tagNodes=row.permission.map((key)=>{
            return h(
              NTag,
              {type: 'success',size:'small'},
              {default: () => keyValus[key]}
            )
          })
          return tagNodes
        }
      },
      {
        title: "操作",
        key: "actions",
        render(row) { //自定义渲染表格内容的函数
          const btns = [
            {title:'编辑',type:'info',fuc:()=>{edit(row)}},
            {title:'删除',type:'error',fuc:()=>{del(row)}},
          ]
          const btnsNode = btns.map((item) => {
            return h(
              NButton,
              {type: item.type,size:'small',onClick:item.fuc},
              {default: () => item.title}
            )
          })
          return btnsNode
        }
      }
    ];
    if(!canUse){
      columnArr.pop()
    }
    return columnArr;
  }
  
  const message = useMessage();
  const dialog = useDialog()
  const router = useRouter()
  const columns=createColumns({
    edit(row) {
      drawerShow.value = true//打开抽屉
      editData.value = row//赋值给编辑数据
    },
    del(row){
      // console.log('删除',row);
      dialog.warning({
        title: '警告，删除后无法找回',
        content: `你确定要删除《${row.roleName}》角色吗？`,
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: async () => {
          let res = await roleDelApi(row._id) //更新数据库
        if(res.data.code==1){
          let list = roleList.value.filter(item=>item._id!=row._id) //更新本地
          roleList.value = list
        }
        }
      })
      
    }
  })
  const pagination = ref(true)
  
//抽屉
const drawerShow = ref(false)
const handleAdd = ()=>{
  drawerShow.value = true
  editData.value = null
}
//列表渲染权限(递归函数)

function routesToKeyValue(routesArr){
  let obj={}
  function loop(arr){//递归调用
    arr.forEach(item=>{
      obj[item.path] = item.label //obj['/cart'] = '购物车管理'
      if(item.children){
        loop(item.children)
      }
    })
  }
  loop(routesArr)
  return obj
}
const keyValus = routesToKeyValue(routes[1].children)
console.log(keyValus);//不需要响应式

//复用新增和编辑的逻辑
const editData = ref(null)//区分新增和编辑
const handleRefresh = (formData)=>{
  //接受子组件实时更新的数据并且刷新列表
  drawerShow.value = false
  let len=roleList.value.length
  for(let i=0;i<len;i++){
    if(roleList.value[i]._id==formData._id){
      roleList.value[i] = formData//更新
      return
    } 
  }
  roleList.value.push(formData)//新增
}

//操作按钮权限控制

  </script>
  
  <style lang="scss" scoped>
  /* 深度选择器 */
  .product-table :deep(.poster){
    height: 50px;
  }
  </style>